/**
 * 获取provinceId, cityId, districtId
 * @param cities 
 * @param code 
 * @returns 
 */
export const getLocationIds = (cities, code) => {

  const findParent = (cities, code) => {
    for (let i = 0; i < cities.length; i++) {
      if (cities[i].id === code) {
        return cities[i].parentId
      }
    }
  }

  let ids = {
    provinceId: '',
    cityId: '',
    districtId: '',
  }

  for (let i = 0; i < cities.length; i++) {
    if (cities[i].id === code) {
      if (code.length > 4) {

        ids = {
          provinceId: findParent(cities, cities[i].parentId),
          cityId: cities[i].parentId,
          districtId: code,
        }
        break
      } else if (code.length > 2) {
        ids = {
          provinceId: cities[i].parentId,
          cityId: code,
          districtId: '',
        }
        break
      } else {
        ids = {
          provinceId: code,
          cityId: '',
          districtId: '',
        }
        break
      }
    }
  }

  return ids

}

export const findCity = (cities, code) => {
  if (code.length <= 4) return code
  for (let i = 0; i < cities.length; i++) {
    if (cities[i].id === code) {
      return cities[i].parentId
    }
  }
}

export const flatCities = (cities: any) => {
  const arr: any[] = []
  for (let i = 0; i < cities.length; i++) {
    arr.push({
      id: cities[i].id,
      parentId: cities[i].parentId,
      name: cities[i].name,
    })
    const children1 = cities[i]?.children || []
    for (let j = 0; j < children1.length; j++) {
      arr.push({
        id: children1[j].id,
        parentId: children1[j].parentId,
        name: children1[j].name,
      })
      const children2 = children1[j]?.children || []
      for (let z = 0; z < children2.length; z++) {
        arr.push({
          id: children2[z].id,
          parentId: children2[z].parentId,
          name: children2[z].name,
        })
      }
    }
  }
  return arr
}


export const findName = (cities: any, code) => {
  for (let i = 0; i < cities.length; i++) {
    if (cities[i].id === code) {
      return cities.name
    }
  }
  return ''
}
